/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Gui;

import Params.ChatMessage;
import Params.ServerSocketItem;
import Params.SocketListener;
import Params.ThreadConnectionSocketChat;
import Params.ThreadConnectionSocketSendFile;
import Params.ThreadConnectionSocketSendMessages;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import sun.awt.windows.ThemeReader;

/**
 *
 * @author ANH PHONG
 */
public class MainSever extends javax.swing.JFrame implements ActionListener, SocketListener, Runnable{

    /**
     * Creates new form MainSever
     */
    public ArrayList<ChatForm> List_CSChat = new ArrayList<ChatForm>();
//    public frmChatServer frmchatServer;
    public static String strPort = "100";
    public static Vector listConnection;
    DefaultListModel Lan_client_chat = new DefaultListModel();
    public MainSever() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        btnAccept = new javax.swing.JButton();
        btnStop = new javax.swing.JButton();
        btnChat = new javax.swing.JButton();
        btnRemote = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        btnExits = new javax.swing.JButton();
        btnStart = new javax.swing.JButton();
        jButton9 = new javax.swing.JButton();
        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        ListLan = new javax.swing.JList();
        jPanel3 = new javax.swing.JPanel();
        jdpDesktop = new javax.swing.JDesktopPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/logo.png"))); // NOI18N
        jLabel1.setText("LAN SUPPORT");

        btnAccept.setText("Accept");
        btnAccept.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);

        btnStop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/player_pause.png"))); // NOI18N
        btnStop.setText("Stop");
        btnStop.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btnStop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStopActionPerformed(evt);
            }
        });

        btnChat.setText("Chat");
        btnChat.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btnChat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChatActionPerformed(evt);
            }
        });

        btnRemote.setText("Remote desktop");
        btnRemote.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);

        jButton5.setText("Screen Capture");
        jButton5.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);

        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/display.png"))); // NOI18N
        jButton6.setText("Monitor Screen");
        jButton6.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);

        btnExits.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/exit.png"))); // NOI18N
        btnExits.setText("Exits");
        btnExits.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btnExits.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnExits.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitsActionPerformed(evt);
            }
        });

        btnStart.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/player_play.png"))); // NOI18N
        btnStart.setText("Start");
        btnStart.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btnStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStartActionPerformed(evt);
            }
        });

        jButton9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/settings.png"))); // NOI18N
        jButton9.setText("Setting");
        jButton9.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnAccept, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnStop, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnChat, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnRemote, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton6, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
                    .addComponent(btnExits, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnStart, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(btnStart, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnAccept, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnStop, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnChat, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnRemote, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnExits, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jScrollPane1.setViewportView(ListLan);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 356, Short.MAX_VALUE)
        );

        jSplitPane1.setLeftComponent(jPanel2);

        jPanel3.setLayout(new java.awt.BorderLayout());
        jPanel3.add(jdpDesktop, java.awt.BorderLayout.CENTER);

        jSplitPane1.setRightComponent(jPanel3);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 621, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(276, 276, 276))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSplitPane1)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(70, 70, 70)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnExitsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitsActionPerformed
        // TODO add your handling code here:
        for(int i=0;i<listConnection.size();i++)
        {
        ServerSocketItem temp =(ServerSocketItem)listConnection.get(i);
        ThreadConnectionSocketChat temp1= (ThreadConnectionSocketChat)temp.getConnectionChat();
            try {
                temp1.GiaiPhong();
            } catch (IOException ex) {
                Logger.getLogger(MainSever.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        this.dispose();
    }//GEN-LAST:event_btnExitsActionPerformed

    private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartActionPerformed
        // TODO add your handling code here:
        // Start Server socket

      initServer();
    }//GEN-LAST:event_btnStartActionPerformed

    private void btnStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStopActionPerformed
        // TODO add your handling code here:
        for(int i=0;i<listConnection.size();i++)
        {
        ServerSocketItem temp =(ServerSocketItem)listConnection.get(i);
        ThreadConnectionSocketChat temp1= (ThreadConnectionSocketChat)temp.getConnectionChat();
            try {
                temp1.GiaiPhong();
            } catch (IOException ex) {
                Logger.getLogger(MainSever.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_btnStopActionPerformed

    private void btnChatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChatActionPerformed
        // TODO add your handling code here:
        Socket temp = (Socket) ListLan.getSelectedValue();
        ChatForm frmchat_Server = new ChatForm(strPort, temp);
        frmchat_Server.setVisible(true);
        this.jdpDesktop.add(frmchat_Server);            // TODO add your handling code here:
        List_CSChat.add(frmchat_Server);
    }//GEN-LAST:event_btnChatActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainSever.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainSever.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainSever.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainSever.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainSever().setVisible(true);
            }
        });
    }
    /**
     * Functions
     */
    private void initServer() {
        try {
            Thread thread = new Thread(this);
            thread.start();
        } catch (Exception ex) {
            Logger.getLogger(MainSever.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList ListLan;
    private javax.swing.JButton btnAccept;
    private javax.swing.JButton btnChat;
    private javax.swing.JButton btnExits;
    private javax.swing.JButton btnRemote;
    private javax.swing.JButton btnStart;
    private javax.swing.JButton btnStop;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton9;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JDesktopPane jdpDesktop;
    // End of variables declaration//GEN-END:variables

    @Override
    public void actionPerformed(ActionEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void onStart() {
    }

    ;

    @Override
    public void onStop() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void onRead(ChatMessage message) {
        for (int i = 0; i < List_CSChat.size(); i++) {
            int temp2 = Integer.parseInt(message.getName());
            int temp = List_CSChat.get(i)._sockhientai.getPort();
            if (temp == temp2) {
                if("exit_1".equals(message.getMessage()))
                {
                    List_CSChat.get(i).dispose();
                    Socket _socktemp=List_CSChat.get(i)._sockhientai;
                    for(int j=0;j<Lan_client_chat.size();j++)
                    {
                        Socket _socktemp2=(Socket)Lan_client_chat.get(j);
                        if(_socktemp2==_socktemp)
                        {
                            Lan_client_chat.remove(j);
                            break;
                        }
                    }
                }
                else {
                    List_CSChat.get(i).onRead(message);
                }
            }
        }
    }

    @Override
    public void run() {
        try {

            ServerSocket SocketChat = new ServerSocket(Integer.parseInt(strPort));
            ServerSocket SocketSendMessages = new ServerSocket(Integer.parseInt(strPort) + 1);
            ServerSocket SocketSendFile = new ServerSocket(Integer.parseInt(strPort) + 2);

            //connectionSocketChat = new ThreadConnectionSocketChat(welcomeSocketChat.accept(), this);  
            //connectionSocketSendFile = new ThreadConnectionSocketSendFile(welcomeSocketSendFile.accept(), this);

            listConnection = new Vector();
            while (true) {
                ServerSocketItem tempServer = new ServerSocketItem();
                Socket client = SocketChat.accept();
                Socket clientm = SocketSendMessages.accept();
                Socket clients= SocketSendFile.accept();
                tempServer.setSOCK(client);
                tempServer.setSOCKM(clientm);
                tempServer.setSOCKS(clients);

                if (client != null) {
                    Lan_client_chat.addElement(client);


                tempServer.setConnectionChat(new ThreadConnectionSocketChat(client,this));
                tempServer.setConnectionMessages(new ThreadConnectionSocketSendMessages(client, this));
                tempServer.setConnectionSocketSendFile(new ThreadConnectionSocketSendFile(clients, this));

                }
                listConnection.addElement(tempServer);
                Thread.yield();
            }

        } catch (IOException ex) {
            Logger.getLogger(MainSever.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
